package com.ihrm.system.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.domain.company.response.RoleResult;
import com.ihrm.domain.system.Role;
import com.ihrm.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/sys/role")
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;

	/**
	 * 添加角色
	 */
	@PostMapping
	public Result add(@RequestBody Role role) {
		//设置保存的企业id
		role.setCompanyId(companyId);
		roleService.save(role);
		return Result.SUCCESS();
	}

	/**
	 * 根据id查询角色
	 */
	@GetMapping("/{roleId}")
	public Result findById(@PathVariable(value = "roleId") String id) {
		Role role = roleService.findById(id);
		RoleResult roleResult = new RoleResult(role);
		return new Result(ResultCode.SUCCESS,roleResult);
	}

	/**
	 * 根据id更新角色
	 */
	@PutMapping("/{roleId}")
	public Result update(@PathVariable(value = "roleId") String id, @RequestBody Role role) {
		role.setId(id);
		roleService.update(role);
		return Result.SUCCESS();
	}

	/**
	 * 查询所有角色列表
	 */
	@GetMapping
	public Result findAll(int page, int size, Role role) {
		//1.指定企业id
		role.setCompanyId(companyId);
		Page<Role> pageRole= roleService.findAll(companyId, page, size);
		//构造返回结果
		PageResult<Role> pageResult = new PageResult<>(pageRole.getTotalElements(),pageRole.getContent());
		return new Result(ResultCode.SUCCESS,pageResult);
	}

	/**
	 * 根据id删除角色
	 */
	@DeleteMapping("/{roleId}")
	public Result delete(@PathVariable(value = "roleId") String id) {
		roleService.delete(id);
		return Result.SUCCESS();
	}


	/**
	 * 为角色分配权限
	 */
	@PutMapping("/assignPerm")
	public Result assignPers(@RequestBody Map<String, Object> map) {
		//1.获取到被分配的角色id
		String roleId=(String) map.get("id");
		//2.获取权限的id列表
		List< String> permIds= (List<String>) map.get("permIds");
		//3.调用service完成权限分配
		roleService.assignPers(roleId,permIds);
		return Result.SUCCESS();
	}
}
